//
//  GYShopDetailes.m
//  GoodLuck
//
//  Created by apple on 2018/5/8.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYShopDetailes.h"
#import "GYNetWorkTools.h"

@implementation GYShopDetailes

+ (NSArray *)jsonShopGoodsDetailes:(NSArray *)source {
    NSMutableArray *models = [NSMutableArray array];
    for (NSDictionary *dic in source) {
        GYShopDetailes *goods = [[GYShopDetailes alloc] initWithDic:dic];
        [models addObject:goods];
    }
    
    return models;
}

- (instancetype)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}

+ (void)loadGoodsDetailsData:(NSString *)goods_id finish:(void (^)(NSArray * _Nullable, NSError * _Nullable))finish {
    [EasyLodingView showLoding];
    [GYNetWorkTools requestGoodsImageDetails:goods_id success:^(NSDictionary *obj) {
        //NSLog(@"商品详情数据加载========%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSArray *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
//            [EasyLodingView hidenLoding];
            NSArray *models = [GYShopDetailes jsonShopGoodsDetailes:datas];
            dispatch_group_t group = dispatch_group_create();
            for (GYShopDetailes *model in models) {
                if ([model.type isEqualToString:@"image"]) {
                    dispatch_group_enter(group);
                    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:model.value] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                        dispatch_group_leave(group);
                    }];
                }
            }
            dispatch_group_notify(group, dispatch_get_main_queue(), ^{
                [EasyLodingView hidenLoding];
                //当所有的图片下载成功之后
                if (models.count == 0) {
                    [EasyTextView showText:@"该商品没有详情!"];
                }else {
                    finish(models,nil);                    
                }
            });
        }else {
            [EasyLodingView hidenLoding];
            [EasyTextView showText:@"亲，您的手机网络不太顺畅喔..."];
            finish(nil,nil);
            NSLog(@"网络加载数据出错....%@",[[obj objectForKey:@"datas"] objectForKey:@"error"]);
        }
    } error:^(NSError *error) {
        finish(nil,error);
        [EasyLodingView hidenLoding];
        [EasyTextView showText:@"亲，您的手机网络不太顺畅喔..."];
        NSLog(@"laodGoodsImageDetailFailed====%@",error);
    }];
}
@end
